package com.jds.test.bio.p2;

/**
 * https://www.cnblogs.com/silyvin/articles/11970337.html
 * Created by joyce on 2019/11/26.
 */
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;


public class Client {

    public static void main(String[] args) throws Exception {

        /**
         * null tcp telay and no flush
         * 1 tcp no delay and noflush
         * 2 tcp delay and flush
         * 3 一个包
         */
        String flag = null;
        if (args != null && args.length > 0) {
            flag = args[0];
        }

        Socket socket = new Socket();

        if ("1".equals(flag))
            socket.setTcpNoDelay(true);

        String host = "49.235.75.155";
        socket.connect(new InetSocketAddress(host, 8000));
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String head = "hello ";
        String body = "world\r\n";
        for (int i = 0; i < 10; i++) {
            long label = System.currentTimeMillis();
            if (!"3".equals(flag)) {
                out.write(head.getBytes());
                out.write(body.getBytes());
                if ("2".equals(flag))
                    out.flush();
            } else {
                out.write((head + body).getBytes());
            }
            String line = reader.readLine();
            System.out.println("RTT:" + (System.currentTimeMillis() - label) + " ,receive:" + line);
            Thread.sleep(1000);
        }

        in.close();
        out.close();
        socket.close();
    }
}